package com.samuel.basics.exception;

import com.samuel.basics.enums.ResultEnum;
import com.samuel.basics.model.ResultVo;
import com.samuel.basics.model.ResultVoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * <p></p>
 *
 * @author aneng huang
 * @since 2020-11-30 14:44:10
 */
@RestControllerAdvice
public class GlobalExceptionHandling {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandling.class);

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = CustomException.class)
    public ResultVo processException(CustomException e) {
        logger.error("位置:{} -> 错误信息:{}", e.getMethod(), e.getLocalizedMessage());
        return ResultVoUtil.error(Objects.requireNonNull(ResultEnum.getByCode(e.getCode())));
    }

    /**
     * 通用异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public ResultVo exception(Exception e) {
        e.printStackTrace();
        logger.error("通用异常：{}", e.getMessage());
        return ResultVoUtil.error(ResultEnum.UNKNOWN_EXCEPTION);
    }
}
